/**
 * @file main.py
 * @brief FastAPI application entry for Meeting Management System.
 * @author Ziyi Wang
 *
 * This file initializes the FastAPI app, mounts routers, static files, templates, and provides login and root endpoints.
 */
from fastapi import FastAPI, Depends, HTTPException, status
from fastapi.security import OAuth2PasswordRequestForm
from fastapi.staticfiles import StaticFiles
from fastapi.templating import Jinja2Templates
from fastapi.middleware.cors import CORSMiddleware
from datetime import timedelta
import os
from pathlib import Path
from sqlalchemy.orm import Session

from .database import engine, get_db, Base
from .models.models import User
from .routers import users, rooms, meetings, frontend
from .auth import authenticate_user, create_access_token, ACCESS_TOKEN_EXPIRE_MINUTES
from .models.schemas import Token

# Create all database tables
Base.metadata.create_all(bind=engine)

/**
 * @brief FastAPI application instance.
 */
app = FastAPI(title="会议管理系统", description="一个基于FastAPI的会议室预订和管理系统")

# CORS settings
app.add_middleware(
    CORSMiddleware,
    allow_origins=["*"],  # 允许所有来源
    allow_credentials=True,
    allow_methods=["*"],  # 允许所有方法
    allow_headers=["*"],  # 允许所有头
)

# 获取静态文件目录的绝对路径
BASE_DIR = Path(__file__).resolve().parent.parent
static_dir = str(BASE_DIR / "static")

# Mount static files
app.mount("/static", StaticFiles(directory=static_dir), name="static")

# Add Jinja2 templates
templates = Jinja2Templates(directory=str(BASE_DIR / "templates"))

# Include routers
app.include_router(users.router)
app.include_router(rooms.router)
app.include_router(frontend.router)  # Must be before meetings.router
app.include_router(meetings.router)

/**
 * @brief Login endpoint for JWT token.
 * @param form_data OAuth2 form data (username, password)
 * @param db Database session
 * @return JWT access token
 * @exception HTTPException 401 if authentication fails
 */
@app.post("/token", response_model=Token)
async def login_for_access_token(form_data: OAuth2PasswordRequestForm = Depends(), db: Session = Depends(get_db)):
    user = authenticate_user(db, form_data.username, form_data.password)
    if not user:
        raise HTTPException(
            status_code=status.HTTP_401_UNAUTHORIZED,
            detail="用户名或密码不正确",
            headers={"WWW-Authenticate": "Bearer"},
        )
    access_token_expires = timedelta(minutes=ACCESS_TOKEN_EXPIRE_MINUTES)
    access_token = create_access_token(
        data={"sub": user.username}, expires_delta=access_token_expires
    )
    return {"access_token": access_token, "token_type": "bearer"}

/**
 * @brief Root endpoint.
 * @return Welcome message.
 */
@app.get("/")
async def root():
    return {"message": "欢迎使用会议管理系统 API"}

if __name__ == "__main__":
    import uvicorn
    uvicorn.run("app.main:app", host="0.0.0.0", port=8000, reload=True) 